package com.bigdata.flink.wordcount;

import com.bigdata.flink.util.StreamEnvUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class WordCount {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamEnvUtil.getEnv();
        DataStreamSource<String> socketSource = StreamEnvUtil.getSocketSource(env);

        SingleOutputStreamOperator<Tuple2<String, Integer>> summed =
                socketSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                            @Override
                            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                                String[] words = value.split(" ");
                                for (String word : words) {
                                    out.collect(new Tuple2<>(word, 1));
                                }
                            }
                        })
                        .returns(Types.TUPLE(Types.STRING, Types.INT))
                        .keyBy(f -> f.f0)
                        .sum(1);

        summed.print();

        env.execute();
    }
}
